<style scoped lang="less">
.scroll-bar{
  position: absolute;
  background: v-bind(color);
  border-radius: 10px;
  transition: opacity ease-in-out 300ms;
  opacity: 0;
  &-show{ opacity: 1 }
}
</style>
<template>
  <div class="scroll-bar" ref="xBar"  :class="{'scroll-bar-show':show}" />
</template>

<script lang="ts" setup>
import {clearTimer, setTimer } from "@/helper";
import {computed, onMounted, ref} from "vue";
import {dragEvent} from "@/helper";

const props = defineProps({
  parentNode: { type:Element, default: null },
  barOptions: { type: Object, default :() => ({}) }
})


const height = computed(() => props.barOptions?.width ?? 5)
const color = computed(() => props.barOptions?.color ?? 'rgb(224,224,224)')
const gap = computed(() => props.barOptions?.gap?? 10)
const position = computed(() => ['top','bottom'].includes(props.barOptions?.position) ? props.barOptions?.position :  'bottom')


let timer:number // 显示定时器
let show = ref(true) // 显示状态
const xBar = ref(null)
let ratio = 1 // 滚动条换算比例
const showBar = () => {
  if(timer) clearTimer(timer)
  show.value = true
  timer = setTimer(() => { show.value = false },300,1)
}
/** renderBar */
const renderBar = () => {
  showBar()
  props.parentNode.addEventListener('mousemove', () => showBar())
  const { scrollTop,offsetWidth,offsetHeight,scrollWidth,scrollLeft } = props?.parentNode
  const barWidth = offsetWidth >= scrollWidth ? 0 : offsetWidth / 1.2
  ratio = (scrollWidth - offsetWidth) / (offsetWidth - barWidth)
  xBar.value.style.left = `${scrollLeft + (scrollLeft/ratio)}px`
  xBar.value.style.width =  `${barWidth}px`
  xBar.value.style.height =  `${height.value}px`
  xBar.value.style.top = scrollTop + (position.value === 'top' ? gap.value : offsetHeight - height.value - gap.value) + 'px'
}
defineExpose({ renderBar })

let parentScrollLeft = 0 // 父节点滚动距离
onMounted(() => {
  dragEvent(
      xBar.value,
      null,
      false,
      event => {
        const { dragX } = event
        props.parentNode.scrollTo({left:parentScrollLeft + dragX * ratio})
      }, () => {
        parentScrollLeft =  props?.parentNode?.scrollLeft
      })
})
</script>

